package cn.wanho.interceptor;


import cn.wanho.util.JWTUtil01;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 通过该拦截器来对除了login请求意外的所有请求进行用户token判定
 */
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //一般为了用户能够把入参作为参数传递，所以token这样值都是作为Header头来传递的
        System.out.println("===过滤器===");
        String token = request.getHeader("token");
        Claims claims = JWTUtil01.parseJWT(token);
        String sid =  claims.get("id",String.class);
        if(null == sid){
            System.out.println("当前token失效");
            return false;
        }else{
            request.setAttribute("userId",Integer.parseInt(sid));
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
